package com.example.b;

import java.io.BufferedOutputStream;  
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.util.Calendar;  
import java.util.Locale;  
  
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;  
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;  
import android.os.Environment;
import android.os.storage.StorageManager;
import android.provider.MediaStore;
import android.text.format.DateFormat;  
import android.util.Log;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.ImageView;  
import android.widget.Toast;  
  
public class MainActivity extends Activity {

    private static String SAVE_REAL_PATH;
    private static Context context;

    private Button button,button1,button2,button3;
    private Bitmap bitmap;
    String name;
  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        button = (Button) findViewById(R.id.button);  
        button.setOnClickListener(new OnClickListener() {  
  
            @Override  
            public void onClick(View v) {  
                // TODO Auto-generated method stub  
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
  
                startActivityForResult(intent, 1);  
            }  
        });  
        button1 = (Button) findViewById(R.id.button1);  
        button1.setOnClickListener(new OnClickListener() {  
  
            @Override  
            public void onClick(View v) {
            	if(null == bitmap){
            		return;
            	}

			//	IImageFilter filter = (IImageFilter) (new ColorToneFilter(0xFFFFFF, 192));
				
				IImageFilter filter = (IImageFilter) (new VideoFilter(3));// 0 1 2 3
				new processImageTask(MainActivity.this, filter).execute();
			
            }  
        });  
        button2 = (Button) findViewById(R.id.button2);  
        button2.setOnClickListener(new OnClickListener() {  
  
            @Override  
            public void onClick(View v) {
            	if(null == bitmap){
            		return;
            	}

				IImageFilter filter = (IImageFilter) (new ColorToneFilter(0xFFFFFF, 192));
				
			//	IImageFilter filter = (IImageFilter) (new VideoFilter(3));// 0 1 2 3
				new processImageTask(MainActivity.this, filter).execute();
			
            }  
        });
        button3 = (Button) findViewById(R.id.button3);  
        button3.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null == bitmap) {
                    return;
                }

                //	IImageFilter filter = (IImageFilter) (new ColorToneFilter(0xFFFFFF, 192));
                //	IImageFilter filter = (IImageFilter) (new VideoFilter(3));// 0 1 2 3
                IImageFilter filter = (IImageFilter) (new FeatherFilter());
                new processImageTask(MainActivity.this, filter).execute();

            }
        });
    } 
	public class processImageTask extends AsyncTask<Void, Void, Bitmap> {
		private IImageFilter filter;
        private Activity activity = null;
		public processImageTask(Activity activity, IImageFilter imageFilter) {
			this.filter = imageFilter;
			this.activity = activity;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		//	textView.setVisibility(View.VISIBLE);
		}

		public Bitmap doInBackground(Void... params) {
			Image img = null;
			try
	    	{
				img = new Image(bitmap);
				if (filter != null) {
					img = filter.process(img);
					img.copyPixelsFromBuffer();
				}
				return img.getImage();
	    	}
			catch(Exception e){
				if (img != null && img.destImage.isRecycled()) {
					img.destImage.recycle();
					img.destImage = null;
					System.gc(); // 提醒系统及时回收
				}
			}
			finally{
				if (img != null && img.image.isRecycled()) {
					img.image.recycle();
					img.image = null;
					System.gc(); // 提醒系统及时回收
				}
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Bitmap result) {
			if(result != null){
				super.onPostExecute(result);
				 ((ImageView) findViewById(R.id.imageView)).setImageBitmap(result);	
			}
		//	textView.setVisibility(View.GONE);
		}
	}
  
    @Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        // TODO Auto-generated method stub  
        super.onActivityResult(requestCode, resultCode, data);  
        if (resultCode == Activity.RESULT_OK) {  
            String sdStatus = Environment.getExternalStorageState();  
            if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用  
                Log.i("TestFile",  
                        "SD card is not avaiable/writeable right now.");  
                return;  
            }  
            name = new DateFormat().format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA)) + ".jpg";
            Toast.makeText(this, name, Toast.LENGTH_LONG).show();  
            Bundle bundle = data.getExtras();  
            bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式  
          
            FileOutputStream b = null;  
            File file = new File("/sdcard/myImage/");  
            file.mkdirs();// 创建文件夹  
            String fileName = "/sdcard/myImage/"+name;  
  
            try {  
                b = new FileOutputStream(fileName);  
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件  
            } catch (FileNotFoundException e) {  
                e.printStackTrace();  
            } finally {  
                try {  
                    b.flush();  
                    b.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
            ((ImageView) findViewById(R.id.imageView)).setImageBitmap(bitmap);// 将图片显示在ImageView里

                saveImage(bitmap);//调用saveImgae 方法 把图片保存在本地

   }
    }

    public static void saveImage(Bitmap bmp)
    {
        File appDir = new File(Environment.getExternalStorageDirectory(),"DCIM");//声明一个文件夹  将文件夹路径在在sdcard的主目录中
        if (!appDir.exists())
        {
            appDir.mkdir();//如果appDir 文件不存在  将在sdcard主目录目录下创建一个文件夹
        }
        String filename =System.currentTimeMillis()+".jpg";//获取时间 给将保存的照片 添加文件名
        File file = new File(appDir,filename);//声明一个文件 文件位于appDir（也就是DCIM） 这个文件夹中
        try {
            FileOutputStream fos = new FileOutputStream(file);//创建文件输出流
            bmp.compress(Bitmap.CompressFormat.JPEG,100,fos);//第一个参数是图片格式，第二个参数是压缩质量，第三个参数是图片文件的输出流。

            fos.flush();
            fos.close();//关闭输出流

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}  